package middleware

import (
	"cloud-storage/lib"
	"cloud-storage/model/mysql"
	"cloud-storage/model/redis"
	jwts "cloud-storage/pkg/jwt"
	"cloud-storage/utils/response"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
	"go.uber.org/zap"
	"strconv"
	"time"
)

func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("x-token")
		if token == "" {
			response.ResponseErrorWithMsg(c, response.CodeError, "未登录或非法访问")
			c.Abort()
			return
		}
		//判断是否在黑名单中
		if mysql.IsBlackList(token) {
			response.ResponseErrorWithMsg(c, response.CodeError, "您的帐户异地登陆或令牌失效")
			c.Abort()
			return
		}
		// parseToken 解析token包含的信息
		claims, err := jwts.ParseToken(token)
		if err != nil {
			if err == jwts.TokenExpired {
				response.ResponseErrorWithMsg(c, response.CodeError, "授权已过期")
				c.Abort()
				return
			}
			response.ResponseErrorWithMsg(c, response.CodeError, err.Error())
			c.Abort()
			return
		}
		if claims.ExpiresAt.Unix()-time.Now().Unix() < claims.BufferTime {
			claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(lib.JWTSetting.ExpiresTime))
			//创建新的token
			newToken, _ := jwts.CreateTokenByOldToken(token, *claims)
			//解析新的token
			newClaims, _ := jwts.ParseToken(newToken)
			c.Header("new-token", newToken)
			c.Header("new-expires-at", strconv.FormatInt(newClaims.ExpiresAt.Unix(), 10))
			//设置是否需要多点登录
			if !lib.AppSetting.UseMultipoint {
				RedisJwtToken, err := redis.GetRedisJwt(newClaims.Phone)
				if err != nil {
					zap.L().Error("get redis jwt failed", zap.Error(err))
				} else { // 当之前的取成功时才进行拉黑操作，拉黑的是即将过期的token
					_ = mysql.JsonInBlackList(mysql.JwtBlackList{Token: RedisJwtToken})
				}
				// 无论如何都要记录当前的活跃状态
				_ = redis.SetRedisJwt(newToken, newClaims.Phone)
			}
		}
		c.Set("phone", claims.Phone)
		c.Next()

	}
}
